const Qs = require("querystring");
const axios = require("axios");
import ErrorCode from "../../modules/ErrorCode";
import { Toast } from "vant";
const http = axios.create({
  baseURL: path,
  timeout: 30000,
  headers: {
    "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8"
  },
  transformRequest: params => Qs.stringify(params)
});

export default http;

//拦截请求
http.interceptors.request.use(config =>
{
  // 处理config
  return config;
});

//拦截响应
http.interceptors.response.use(
  // 成功 : err.code >=200 || err.code <=300
  function (res)
  {
    const body = res.data;

    if (body.status != 1) {
      console.log(ErrorCode[body.status]);
      Toast(ErrorCode[body.status]);
      //   alert("处理服务器返回的错误码: ErrorCode");
      return Promise.reject();
    }

    //处理服务器返回的数据
    return Promise.resolve(body);
  },

  // 失败: status > 300
  function (err)
  {
    if (err.code === "ECONNABORTED") {
      Toast("网络连接超时");
    }
    if (err.response) {
      const res = err.response;
      console.log(res.status); // 404, 500...
      if (res.status == "404") {
        Toast("网络连接失败，请检查网络");
      }
      if (res.status == "500") {
        Toast("服务器异常,请稍后再试");
      }
    }
    return Promise.reject(err);
  }
);
